import json
import logging
import uuid

from utils import db_util
from controller import base_handler

verify_field_list = ("id", "interface_id", "verify_param", "verify_regex", "verify_desc", "verify_status")


class ListHandler(base_handler.BaseHandler):
    def get(self):
        page = self.get_query_argument("page", "1")
        perPage = self.get_query_argument("perPage", "100")
        params = []
        where_sql = " where"
        field_value = self.get_query_argument("interface_id", None)
        if field_value:
            params.append(field_value)
            where_sql += " %s = ? and" % "interface_id"

        sql = """select * from crud_verify """
        if len(params) > 0:
            sql += where_sql[0:-3]
        else:
            params = None

        sql += " order by verify_param"

        rows = db_util.execute_page(sql, int(page), int(perPage), params)

        res = {"status": 0, "message": "ok",
               "data": {"page": page, "total": rows["total"], "rows": rows["items"]}}

        self.set_response(res, 200)


class AddHandler(base_handler.BaseHandler):
    def post(self):
        logging.info(self.request.body.decode())
        req_body = json.loads(self.request.body.decode())

        v_id = uuid.uuid1().hex
        params = [v_id]
        field_names = ["id"]
        field_values = ["?"]
        for field_name in verify_field_list:
            field_value = req_body.get(field_name, None)
            if field_value:
                field_names.append(field_name)
                field_values.append("?")
                params.append(field_value)

        sql = """ insert into crud_verify (%s)values(%s)""" % (",".join(field_names), ",".join(field_values))

        flag = db_util.execute_update(sql, params=params)
        if flag is True:
            res = {"status": 0, "message": "添加成功"}
        else:
            res = {"status": 1, "message": "添加失败:%s" % db_util.get_last_error()}

        self.set_response(res, 200)


class EditHandler(base_handler.BaseHandler):
    def post(self):
        logging.info(self.request.body.decode())
        req_body = json.loads(self.request.body.decode())
        v_id = req_body.get("id", None)
        param = []
        up_sql = ""
        for field_name in verify_field_list:
            field_value = req_body.get(field_name, None)
            if field_value:
                param.append(field_value)
                up_sql += "%s=?," % field_name
        param.append(v_id)

        sql = """update crud_verify set %s where id=?""" % (up_sql[0:-1])
        flag = db_util.execute_update(sql, param)
        if flag is True:
            res = {"status": 0, "message": "修改成功"}
        else:
            res = {"status": 1, "message": "修改失败:%s" % db_util.get_last_error()}

        self.set_response(res, 200)


class DelHandler(base_handler.BaseHandler):
    def post(self):
        logging.info(self.request.body.decode())
        req_body = json.loads(self.request.body.decode())
        flag = False
        v_id = req_body.get("id", None)

        if v_id and v_id != "":
            sql = "delete from crud_verify where id =?"
            flag = db_util.execute_update(sql, [v_id])
        if flag is True:
            res = {"status": 0, "message": "删除成功"}
        else:
            res = {"status": 1, "message": "删除失败:%s" % db_util.get_last_error()}

        self.set_response(res, 200)
